package com.heima.juc.n4;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : leimingchao
 * @date Date : 2022年01月11日 19:37
 */
@Slf4j(topic = "c.TestThreadSafe")
public class TestThreadSafe {

    static final int THREAD_NUMBER = 1;
    static final int LOOP_NUMBER = 200;

    public static void main(String[] args) {
        // ThreadUnsafe threadUnsafe = new ThreadUnsafe();
        // ThreadSafe threadSafe = new ThreadSafe();

        ThreadSafeSubClass threadSafeSubClass = new ThreadSafeSubClass();
        for (int i = 0; i < THREAD_NUMBER; i++) {
            new Thread(() -> {
                // threadUnsafe.method1(LOOP_NUMBER);
                // threadSafe.method1(LOOP_NUMBER);
                threadSafeSubClass.method1(LOOP_NUMBER);

            },"Thread" + (i + 1)).start();
        }
    }
}

class ThreadUnsafe {

    List<String> list = new ArrayList<>();

    public void method1(int loopNumber) {
        for (int i = 0; i < loopNumber; i++) {
            method2();
            method3();
        }
    }

    private void method2() {
        list.add("1");
    }

    private void method3() {
        list.remove(0);
    }
}

class ThreadSafe {

    public final void method1(int loopNumber) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < loopNumber; i++) {
            method2(list);
            method3(list);
        }
    }

    private void method2(List<String> list) {
        list.add("1");
    }

    private void method3(List<String> list) {
        list.remove(0);
    }
}

class ThreadSafeSubClass extends ThreadSafe {

    public void method3(List<String> list) {
        new Thread(() ->
                list.remove(0)
        ).start();
    }
}


